<?php


namespace App\Http\Controllers\Alipay;


use App\Models\MemberOther;
use App\Models\Order;
use App\Models\OrderDepict;
use App\Models\OrderGoods;
use App\Models\OrderLease;
use App\Models\OrderLeasePartial;
use App\Models\ShopPaylog;
use App\Models\ShopSms;
use App\Models\ShopUser;
use App\Models\SmsTemplate;
use App\Models\OrderInsurancePay;
use App\Services\AlipayMiniAppService;
use App\Services\AlipayService;
use App\Services\ChargeService;
use App\Services\CommonService;
use App\Services\OrderService;
use App\Services\GoodsService;
use App\Services\WechatService;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;

class PayController extends BaseController
{
    /**
     * 提前还款-主动支付
     * @param Request $request
     * @return false|string
     */
    public function prepaymentPay(Request $request)
    {
        try {
            $orderId = $request->input('orderId', '');
            $leaseId = $request->input('leaseId', '');
            if (!$orderId || !$leaseId) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
            }
            $order = Order::where(['id' => $orderId])->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_WITHHOLD_OR_PAY))
                ->select('mini_id', 'trade_no', 'seller_id', 'uid', 'status', 'pact_url', 'sign_status',  'withhold_status')->first();
            $order = obToArray($order);
            if (!$order) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '待支付订单不存在');
            }
            if ($order['status']<10&&empty($order['pact_url'])){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请签署合同后再进行支付');
            }
            if ($order['status'] < 10 && empty($order['withhold_status'])) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请签署租赁宝后进行支付');
            }

            if ($order['status'] < 10 ) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请前往订单列表点击【立即支付】进行支付');
            }

            $leaseId = explode(',', $leaseId);
            if (!$leaseId || !is_array($leaseId)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '租期格式错误');
            }
            $lease = OrderLease::where(['order_id' => $orderId])->whereIn("id", $leaseId)->select('which_period', 'rent', 'paid_rent', 'status', 'overdue_days', 'overdue_amount')->get();
            $lease = obToArray($lease);
            if (!$lease) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '账单不存在');
            }
            $totalRent = 0;
            $leaseNum = [];
            foreach ($lease as $item) {
                //判断租期状态
                if (!in_array($item['status'], [OrderLease::ORDER_LEASE_STATUS_NOPAY, OrderLease::ORDER_LEASE_STATUS_REFUNDED, OrderLease::ORDER_LEASE_STATUS_OVERDUE])) {
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '租期包含不可支付账单');
                }
                $totalRent += bcsub($item['rent'] + $item['overdue_amount'], $item['paid_rent'], 2);
                $leaseNum[] = $item['which_period'];
            }

            $goodsTitle = OrderGoods::where(['order_id' => $orderId])->value('goods_title');
            $shopName = ShopUser::where(['member_id' => $order['seller_id']])->value('shopname');
            $cert_name = MemberOther::where('id', $order['uid'])->value('cert_name');

            $payData['mini_id'] = $order['mini_id'];
            $payData['orderNo'] = $order['trade_no'];
            $payData['leaseId'] = implode(',', $leaseId);
            $payData['subject'] = '主动支付' . $goodsTitle . '|' . $shopName . '|' . $cert_name;
            $payData['totalAmount'] = sprintf('%.2f', $totalRent);
            $payData['userAlipayUId'] = $this->member['user_id'];
            $payData['orderDescribe'] = '主动支付第' . implode(',', $leaseNum) . '期';
            $payData['notifyUrl'] = config('alipay.callbackDomain') . CommonService::NOTICE_XXZ_URL_PAY;

            $miniId = AlipayMiniAppService::getInstance()->getMiniId();
            $result = AlipayService::alipayPrepaymentPay($miniId, $payData);

            if ($result['status']) {
                $returnData['tradeNo'] = $result['data']['trade_no'];
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '唤起成功', $returnData);
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '唤起支付失败');
            }
        } catch (\Exception $exception) {
            Log::error("支付失败", [
                'exception' => $exception->getMessage()
            ]);
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '支付失败');
        }

    }

    /**
     * 碎屏险购买
     * @param Request $request
     * @return false|string
     */
    public function orderInsuranceBuy(Request $request)
    {
        // try {
        $orderId = $request->input('orderId', '');
        $insurance = $request->input('insurance', '');
        if (!$orderId) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }


        $order = obToArray(
            Order::where(['id' => $orderId])
                ->select('id', 'mini_id', 'trade_no', 'seller_id', 'status', 'is_insurance_choose')
                ->first()
        );

        $totalAmount = GoodsService::getGoodsInsurance($insurance);

        $goodsTitle = OrderGoods::where(['order_id' => $orderId])->value('goods_title');
        $trade_no = createNo();
        $payData['orderNo'] = $trade_no;
        $payData['leaseId'] = $order['id'];
        $payData['subject'] = '支付' . $goodsTitle;
        $payData['totalAmount'] = $totalAmount;
        $payData['userAlipayUId'] = $this->member['user_id'];
        $payData['orderDescribe'] = '支付' . $goodsTitle;
        $payData['notifyUrl'] = config('alipay.callbackDomain') . CommonService::NOTICE_ORDER_INSURANCE_URL_PAY;

        $miniId = $order['mini_id'];
        $result = AlipayService::alipayPrepaymentPay($miniId, $payData, time());

        if ($result['status']) {
            $addData = array(
                'amount' => $totalAmount,
                'out_trade_no' => $trade_no,
                'order_id' => $order['id'],
                'request' => json_encode($payData),
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            );
            OrderInsurancePay::insert($addData);
            $returnData['tradeNo'] = $result['data']['trade_no'];
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '唤起成功', $returnData);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '唤起支付失败');
        }
        // }catch (\Exception $exception){
        //     return ReturnMsg(CommonService::HTTP_CODE_FAIL,'支付失败');
        // }
    }


    //部分还款详情
    public function leasePartialDetail(Request $request){

        if(empty($request['leaseId'])||empty($request['orderId'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }
        $OrderLease= OrderLease::where('id',$request['leaseId'])->where('order_id',$request['orderId'])
            ->select(
                'id','which_period','status','order_id','begin_time','end_time','rent','paid_rent','overdue_days','overdue_amount'
            )
            ->first();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if($OrderLease){
            $OrderLease['begin_time'] = date('Y-m-d',$OrderLease['begin_time']);
            $returnData['lease_total_amount'] = bcsub($OrderLease['rent']+$OrderLease['overdue_amount'],$OrderLease['paid_rent'],2);
            $returnData['lease_total_amount_minimum'] = bcmul($returnData['lease_total_amount'],0.1,2);
            $returnData =array_merge($returnData,$OrderLease);

            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$returnData);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'获取失败');
        }
    }
    /**
     * 分期部分还款
     */
    public function submitLeasePartial(Request $request)
    {
        if (empty($request['partialAmount']) || empty($request['leaseId']) || empty($request['orderId'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }

        if (!is_numeric($request['partialAmount'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '金额填写有误');
        }
        $OrderLease = OrderLease::where('id', $request['leaseId'])->where('order_id', $request['orderId'])
            ->select(
                'id', 'which_period', 'status', 'order_id', 'rent', 'overdue_days', 'overdue_amount'
            )
            ->first();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if (empty($OrderLease)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }

        if ($OrderLease['status'] != 4) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '未逾期，请足额还款');
        }

        if ($OrderLease['status'] == 1 && !empty($OrderLease['pay_time'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '该期已支付');
        }

        $order = Order::where(['id' => $OrderLease['order_id']])
            ->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_WITHHOLD_OR_PAY))
            ->select('mini_id', 'trade_no', 'seller_id', 'status', 'pact_url', 'sign_status')
            ->first();
        $order = obToArray($order);
        if (!$order) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '待支付订单不存在');
        }
        if ($order['sign_status'] != 2 || empty($order['pact_url'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请签约合同后获取收款码');
        }
        $order_no = $order['trade_no'];
        $add = [
            'lease_id' => $request['leaseId'],
            'partial_amount' => $request['partialAmount'],
            'pay_type' => 2,
            'create_time' => time(),
            'reason' => '用户发起支付',
            'out_trade_no' => $order_no . '|' . time(),
        ];
        $partial_amount = OrderLeasePartial::where('lease_id', $request['leaseId'])->where('status', OrderLeasePartial::STATUS_ISPAY)->sum('partial_amount');

        $lease_total_amount = bcadd($OrderLease['rent'], $OrderLease['overdue_amount'], 2);

        if (bcadd($request['partialAmount'], $partial_amount, 2) > $lease_total_amount) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请务大于可还金额');
        }
        if (($request['partialAmount']) < bcmul($OrderLease['rent'] + $OrderLease['overdue_amount'] - $partial_amount, 0.1, 2)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请务小于最低还款金额');
        }
        $res = OrderLeasePartial::insert($add);

        $goodsTitle = OrderGoods::where(['order_id' => $OrderLease['order_id']])->value('goods_title');
        $shopName = ShopUser::where(['member_id' => $order['seller_id']])->value('shopname');


        $payData['orderNo'] = $add['out_trade_no'];
        $payData['leaseId'] = $OrderLease['id'];
        $payData['subject'] = '主动支付部分还款' . $goodsTitle . '|' . $shopName;
        $payData['totalAmount'] = sprintf('%.2f', $request['partialAmount']);
        $payData['userAlipayUId'] = $this->member['user_id'];
        $payData['orderDescribe'] = '部分还款主动支付第' . $OrderLease['which_period'] . '期';
        $payData['notifyUrl'] = config('alipay.callbackDomain') . '/Supplier/Notice/orderLeasePartialNotify';

        $miniId = $order['mini_id'];
        $result = AlipayService::alipayPrepaymentPay($miniId, $payData, true);
        if ($result['status']) {
            $returnData['trade_no'] = $result['data']['trade_no'];
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '唤起成功', $returnData);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '唤起支付失败');
        }


    }

    /**
     * 还款
     */
    public function submitShopPay(Request $request){

//        if(empty($request['amount'])||$request['amount']<1){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'消费金额不能少于￥1');
//        }

        if(!is_numeric($request['amount'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'金额填写有误');
        }
        $order_sn  = date('YmdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $add = [
            'other_admin_id'=>$request['customer_id']??'0',
            'amount'=>$request['amount'],
            'uid'=>$this->member['id'],
            'create_time'=>time(),
            'out_trade_no'=>'A'.$order_sn,
        ];

        $res=ShopPaylog::insert($add);

        $payData['orderNo'] = $add['out_trade_no'];
        $payData['subject']   = '门店消费';
        $payData['totalAmount'] = sprintf('%.2f',$request['amount']);
        $payData['userAlipayUId'] = $this->member['user_id'];
        $payData['orderDescribe'] = '';
        $payData['notifyUrl'] = config('alipay.callbackDomain').'/Alipay/Notice/shopPayNotify';
        $miniId = $order['mini_id'];
        $result = AlipayService::alipayPrepaymentPay($miniId,$payData,true);
        if($result['status']){
            $returnData['trade_no'] = $result['data']['trade_no'];
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'唤起成功',$returnData);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'唤起支付失败');
        }


    }

    /**
     * 支付第一期租金押金碎屏险
     * @param Request $request
     * @return array|false|string
     */
    public function submitOrderShouldPayDetail(Request $request)
    {
        $orderDetail=Order::query()->from('sp_order_2 as o')
            ->leftJoin('sp_order_goods_2 as og','og.order_id','=','o.id')
            ->where('o.id',$request['order_id'])
            ->select('og.cash_pledge','o.is_insurance_choose_custom','o.prepayment_total','o.is_insurance_choose','o.status')->first();
        if($orderDetail['status']!='3'){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'待支付订单状态下才能支付');
        }
        $rent=[];
        if($orderDetail['prepayment_total']>0){
            $rent=OrderLease::query()->where('order_id',$request['order_id'])->where('which_period',1)
                ->select('rent','begin_time','status')->first();
            $rent['begin_time']=date('Y-m-d',$rent['begin_time']);
            $rent['month_total']=OrderLease::query()->where('order_id',$request['order_id'])->count();
        }


        $orderDetail['cash_pledge']=$orderDetail['cash_pledge']??0;
        $is_insurance_choose_custom=GoodsService::getGoodsInsurance($orderDetail['is_insurance_choose'],$orderDetail['is_insurance_choose_custom']);
        $orderDetail['is_insurance_choose_custom']=$is_insurance_choose_custom;
        if(!$rent){
            $orderDetail['total_amount']=bcadd($is_insurance_choose_custom,$orderDetail['cash_pledge'],2);
        }else{
            $orderDetail['total_amount']=bcadd($rent['rent']+$is_insurance_choose_custom,$orderDetail['cash_pledge'],2);
            $orderDetail=array_merge($orderDetail->toArray(), $rent->toArray());
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$orderDetail);

    }
    /**
     * 支付押金
     * @param Request $request
     * @return false|string
     * @throws \Exception
     */

    public function submitOrderDepictPay(Request $request){

        if(!is_numeric($request['order_id'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请选择订单');
        }

        $miniId = AlipayMiniAppService::getInstance()->getMiniId();

        $order=Order::query()->where('id',$request['order_id'])->where('uid',$this->member['id'])
            ->select('id','mini_id','uid','is_insurance_choose_custom','is_insurance_choose','prepayment_total','sign_status','pact_url','status','withhold_status')->first();

        if(!$order){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if ($order['status']<10&&($order['sign_status']!=2||empty($order['pact_url']))){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请确认签约合同后再进行支付');
        }

        if ($order['status']<10&&empty($order['withhold_status'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请签署租赁宝后进行支付');
        }

        if(!$this->member['idcard_back']||!$this->member['idcard_front']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请前往订单详情页点击上传身份证件');
        }



        $orderDepict=OrderDepict::query()->where('order_id',$request['order_id'])->where('user_id',$this->member['id'])
            ->select('alipay_trade_no','status','out_trade_no','amount','id')->first();

        if($orderDepict['status']==1&&!empty($orderDepict['alipay_trade_no'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'押金已支付');
        }

        $cash_pledge=OrderGoods::query()->where('order_id',$request['order_id'])->value('cash_pledge');

//        if($cash_pledge<=0&&$order['is_insurance_choose_custom']<=0){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该订单无需支付押金');
//        }

        $rent=0;
        if($order['prepayment_total']>=0){
            $rent=OrderLease::query()->where('order_id',$request['order_id'])->where('which_period',1)
                ->where('status','<>',1)->value('rent');
        }

        $rent=$rent??0;
        $is_insurance_choose_custom=GoodsService::getGoodsInsurance($order['is_insurance_choose'],$order['is_insurance_choose_custom']);

        $amount=bcadd($cash_pledge+$rent,$is_insurance_choose_custom,2);

        $order_sn  = date('YmdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);


        $add = [
            'order_id'=>$order['id'],
            'amount'=>$amount,
            'rent_first_amount'=>$rent,
            'screen_amount'=>$is_insurance_choose_custom,
            'deposit_amount'=>$cash_pledge,
            'user_id'=>$this->member['id'],
            'create_time'=>date('Y-m-d H:i:s'),
            'out_trade_no'=>'B'.$order_sn,
        ];
        if(!$orderDepict){
            $OrderDepictModel=new OrderDepict();
            $res=$OrderDepictModel->createOrderDepict($add);
            if(!$res){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单创建失败');
            }
        }else{
            if($amount!=$orderDepict['amount']){
                $res=OrderDepict::query()->where('id',$orderDepict['id'])->update($add);
                if(!$res){
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单创建失败');
                }
                $orderDepict['out_trade_no']=$add['out_trade_no'];
            }
        }

        $payData['orderNo'] = $orderDepict?$orderDepict['out_trade_no']:$add['out_trade_no'];
        $payData['subject']   = '费用';
        $payData['totalAmount'] = $amount;
        $payData['userAlipayUId'] = $this->member['user_id'];
        $payData['orderDescribe'] = '';
        $payData['notifyUrl'] = config('alipay.callbackDomain').'/Alipay/Notice/orderDepictNotify';
//        $miniId = $order['mini_id'];
        $result = AlipayService::alipayPrepaymentPay($miniId,$payData,true);
        if($result['status']){
            $returnData['trade_no'] = $result['data']['trade_no'];
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'唤起成功',$returnData);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'唤起支付失败');
        }


    }

}
